package com.example.java_gobang.game;

import com.example.java_gobang.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.media.jfxmediaimpl.HostUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LXW
 * Date: 2022-08-06
 * Time: 11:50
 */
@Component
public class Matcher {
    private ObjectMapper objectMapper = new ObjectMapper();
    // 三个匹配队列
    private Queue<User> normalQueue = new LinkedList<>();
    private Queue<User> highQueue = new LinkedList<>();
    private Queue<User> veryHighQueue = new LinkedList<>();
    // 玩家在线状态
    @Autowired
    private OnlineUserManager onlineUserManager;

    @Autowired
    private RoomManager roomManager;

    /**
     * 将用户加入匹配队列
     * @param user
     * @throws InterruptedException
     */
    public void add(User user) throws InterruptedException {
        if (user.getScore() < 2000) {
            synchronized (normalQueue) {
                normalQueue.offer(user);
                normalQueue.notify();
            }
            System.out.println("[Matcher] " + user.getUserId() + " 进入 normalQueue!");
        } else if (user.getScore() < 3000) {
            synchronized (highQueue) {
                highQueue.offer(user);
                highQueue.notify();
            }
            System.out.println("[Matcher] " + user.getUserId() + " 进入 highQueue!");
        } else {
            synchronized (veryHighQueue) {
                veryHighQueue.offer(user);
                veryHighQueue.notify();
            }
            System.out.println("[Matcher] " + user.getUserId() + " 进入 veryHighQueue!");
        }
    }

    /**
     * 将用户从匹配队列中移除
     * @param user
     */
    public void remove(User user) {
        if (user.getScore() < 2000) {
            removeFromQueue(normalQueue, user);
            System.out.println("[Matcher] " + user.getUserId() + " 移出 normalQueue!");
        } else if (user.getScore() < 3000) {
            removeFromQueue(highQueue, user);
            System.out.println("[Matcher] " + user.getUserId() + " 移出 highQueue!");
        } else {
            removeFromQueue(veryHighQueue, user);
            System.out.println("[Matcher] " + user.getUserId() + " 移出 veryHighQueue!");
        }
    }

    private void removeFromQueue(Queue<User> queue, User user) {
        synchronized (queue) {
            queue.remove(user);
        }
    }

    /**
     * 三个线程不断去调用HandlerMatch方法
     */
    private Matcher() {
        // 这三个线程各自执行各自的
        Thread t1 = new Thread() {
            @Override
            public void run() {
                while (true) {
                    handlerMatch(normalQueue);
                }

            }
        };
        t1.start();

        Thread t2 = new Thread() {
            @Override
            public void run() {
                while (true) {
                    handlerMatch(highQueue);
                }

            }
        };
        t2.start();

        Thread t3 = new Thread() {
            @Override
            public void run() {
                while (true) {
                    handlerMatch(veryHighQueue);
                }

            }
        };
        t3.start();
    }

    /**
     * 处理用户匹配
     * @param matchQueue
     */
    public void handlerMatch(Queue<User> matchQueue) {
        synchronized (matchQueue) {
            try {
                // 保证只有一个玩家在队列的时候, 不会被出队列. 从而能支持取消功能.
                while (matchQueue.size() < 2) {
                    matchQueue.wait();
                }
                // 1. 尝试获取两个元素
                User player1 = matchQueue.poll();
                User player2 = matchQueue.poll();
                System.out.println("匹配出两个玩家: " + player1.getUserId() + ", " + player2.getUserId());
                // 2. 检查玩家在线状态(可能在匹配中玩家突然关闭页面)
                WebSocketSession session1 = onlineUserManager.getFromGameHall(player1.getUserId());
                WebSocketSession session2 = onlineUserManager.getFromGameHall(player2.getUserId());
                if (session1 == null) {
                    // 如果玩家1 下线, 则把玩家2 放回匹配队列
                    matchQueue.offer(player2);
                    return;
                }
                if (session2 == null) {
                    // 如果玩家2 下线, 则把玩家1 放回匹配队列
                    matchQueue.offer(player1);
                    return;
                }
                if (session1 == session2) {
                    // 如果得到的两个 session 相同, 说明是同一个玩家两次进入匹配队列
                    // 例如玩家点击开始匹配后, 刷新页面, 重新再点开始匹配
                    // 此时也把玩家放回匹配队列
                    matchQueue.offer(player1);
                    return;
                }

                // 3. 将这两个玩家加入到游戏房间中.
                Room room = new Room();
                roomManager.add(room, player1.getUserId(), player2.getUserId());
                // 4. 给玩家1 发回响应数据
                MatchResponse response1 = new MatchResponse();
                response1.setMessage("matchSuccess");
                session1.sendMessage(new TextMessage(objectMapper.writeValueAsString(response1)));
                // 5. 给玩家2 发回响应数据
                MatchResponse response2 = new MatchResponse();
                response2.setMessage("matchSuccess");
                session2.sendMessage(new TextMessage(objectMapper.writeValueAsString(response2)));
            } catch (InterruptedException | IOException e) {
                e.printStackTrace();
            }
        }
    }
}
